package com.doge.walknovel.core.account

import androidx.lifecycle.LiveData
import com.doge.walknovel.api.model.UserInfo
import com.doge.walknovel.business.login.LoginActivity
import com.doge.walknovel.utils.*


//  eyJhbGciOiJSUzI1NiJ9.eyJ0IjoxNjIxNDI2Mjc1OTQ0LCJiIjoxfQ.SIcOb_dPw6YaENH8mmMnVAccuX2lSmgu0w_FDLUXWm2EJRN-bnLOFeMZsKu32I42D8n6Atzq0XKcDd0mqsXCMK0IlQGFdzng9V-TubC1f6CTA5-f-GYN2gXbKLkm_zM53XlMfd-f3F51_-0EpQ97esqJGwZNctD_pYaUSqoKgZA

object AccountHelper {
    private const val folder = "acc"
    private const val key = "t"
    private var timestamp = 0L
    private var t: String? = null
    val token: String get() = getUToken() ?: ""
    val selfInfo: LiveData<UserInfo?> = AppUserViewModel.get().user
    val self: UserInfo get() = AppUserViewModel.get().self()

    private val isLogin: Boolean get() = self.isLogin

    fun updateUToken(token: String?) {
        t = token
        runOnIO { spWrite(key, token ?: "", folder) }
    }

    private fun getUToken(): String? {
        return t ?: spReadString(key, null, folder).also { t = it }
    }

    fun requiredLogin(callback: () -> Unit = {}) {
        require(isMainThread())
        if (!isLogin) {
            if (System.currentTimeMillis() - timestamp > 1500) {
                LoginActivity.start(Activities.top ?: appContext)
            }
            return
        }
        callback()
    }
}
